<template>
  <el-dialog v-if="dialog" title="我的图片" custom-class="out-dialog" :close-on-click-modal="false" append-to-body :visible.sync="dialog">
    <div>
      <el-button type="primary" class="mb10" @click="openAddDialog">添加</el-button>
      <div class="goods-Material">
        <div class="goods-Material_left" >
          <el-input v-model="groupName" class="search-btn" placeholder="搜索分组名称" />
          <el-tree ref="tree" :data="treeList" :highlight-current="true" :expand-on-click-node="false" default-expand-all :filter-node-method="filterNode" @node-click="handleNodeClick">
            <span slot-scope="{ data }" class="custom-tree-node">
              <span>{{ data.name }} ({{ data.sourceCount }})</span>
            </span>
          </el-tree>
        </div>
        <div class="goods-Material_right">
          <ul>
            <li v-for="(item, index) in list" :key="index" style="width:120px;display:inline-block;margin:0 10px 10px 0;" @click="chooseImg(item, index)">
              <div v-if="checkList.indexOf(item.path) != -1" class="item active" style="box-sizing:border-box;width:120px;height:120px;position:relative;border:2px solid #07d;position:relative;">
                <img :src="item.path" alt="" style="width:100%;height:100%;">
                <div style="position:absolute;display:block;content:'';right:-1px;top:0;border:14px solid #07d;border-left-color:transparent;border-bottom-color:transparent;z-index:1;" />
                <span style="position:absolute;top:2px;right:2px;color:#fff;z-index:2;">
                  {{ checkList.indexOf(item.path) + 1 }}
                </span>
              </div>
              <div v-else class="item" style="box-sizing:border-box;width:120px;height:120px;position:relative;border:2px solid rgba(1,1,1,0);">
                <img :src="item.path" alt="" style="width:100%;height:100%;">
              </div>
            </li>
          </ul>
          <vxe-pager
            :current-page.sync="searchParams.pageNum"
            :page-size.sync="searchParams.pageSize"
            :total="total"
            :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            @page-change="getMaterialList"
          />
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialog = false">取 消</el-button>
      <el-button type="primary" @click="clickSure">确 定</el-button>
    </div>
    <el-dialog v-if="addDialog" custom-class="out-dialog" title="添加" :visible.sync="addDialog" :close-on-click-modal="false" append-to-body>
      <el-form ref="addForm" :model="addParams" :rules="addRules" label-width="7rem">
        <el-row>
          <el-col :span="13">
            <el-form-item prop="parentId" label="所在分组">
              <el-select v-model="addParams.parentId" filterable placeholder="请选择">
                <el-option v-for="item in selectList" :key="item.index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="sources" label="选择图片">
              <Upload ref="meterial" :multiple="true" :limit="99999" :file-filter="['jpg', 'jpeg', 'png', 'icon', 'gif', 'bmp', 'JPG', 'JPEG', 'PNG', 'ICON', 'GIF', 'BMP']" @setKey="getUrl" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="clickSureAdd">确 定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { getMaterialGroupList, getMaterialList, addMaterial } from '@/api/file/source'
import Upload from '@/components/upload'

export default {
  components: {
    Upload
  },
  props: {
    max: {
      required: false,
      type: Number,
      default: () => 1
    },
    chooseList: {
      required: false,
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      checkList: [],
      active: 1,
      dialog: false,
      groupName: '',
      searchParams: {
        parentId: '',
        type: 1,
        rule: 1,
        pageNum: 1,
        pageSize: 20
      },
      total: 1,
      list: [],
      treeList: [],
      selectList: [],
      addParams: {
        type: 1,
        parentId: '',
        sources: []
      },
      addDialog: false,
      addRules: {
        parentId: [{ required: true, message: '请选择分组', trigger: 'change' }],
        sources: [{ type: 'array', required: true, message: '请选择图片', trigger: 'change' }],
        name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }]
      }
    }
  },
  watch: {
    groupName(val) {
      this.$refs.tree.filter(val)
    },
    dialog(val) {
      if (val) {
        this.checkList = JSON.parse(JSON.stringify(this.chooseList))
        this.getMaterialGroupList()
      }
    }
  },
  methods: {
    getUrl(arr) {
      const arr1 = []
      arr.forEach(item => {
        arr1.push({
          name: item.url,
          path: item.name,
          contentType: item.zxfUrl.split('.')[1]
        })
      })
      this.addParams.sources = arr1
      if (arr.length === 0) {
        this.$refs.addForm.validateField('sources')
      } else {
        this.$refs.addForm.clearValidate('sources')
      }
    },
    openAddDialog() {
      this.addParams.parentId = ''
      this.addParams.sources = []
      this.addDialog = true
    },
    clickSureAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          addMaterial(this.addParams).then(res => {
            this.$message.success('添加成功！')
            this.addDialog = false
            this.searchParams.pageNum = 1
            this.getMaterialList()
            this.getMaterialGroupList(1)
          })
        }
      })
    },
    chooseImg(item, index) {
      if (this.max === 1) {
        this.checkList = [item.path]
      } else {
        if (this.checkList.indexOf(item.path) !== -1) {
          this.checkList.splice(this.checkList.indexOf(item.path), 1)
        } else {
          if (this.max === this.checkList.length) {
            this.$message.error('已超出最大勾选数量')
            return false
          }
          this.checkList.push(item.path)
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    getMaterialList() {
      getMaterialList({ ...this.searchParams }).then(res => {
        this.total = res.total
        this.list = res.records
      })
    },
    getMaterialGroupList(type = 0) {
      getMaterialGroupList({ type: 1 }).then(res => {
        this.treeList = res
        this.selectList = res[0].children
        if (res.length !== 0 && type === 0) {
          this.searchParams.parentId = ''
          this.getMaterialList()
        }
      })
    },
    handleNodeClick(data) {
      this.searchParams.parentId = data.name === '全部' ? '' : data.id
      this.searchParams.pageNum = 1
      this.getMaterialList()
    },
    clickSure() {
      if (this.checkList.length === 0) {
        this.$message.error('请选择图片')
        return false
      }
      console.log('this.checkList', this.checkList)
      this.$emit('getUrl', this.checkList)
      this.$emit('chooseImagesEnd', { data: this.checkList }
      )
      this.dialog = false
    }
  }
}
</script>

<style lang="scss">
.goods-Material {
  display: flex;
  justify-content: space-between;
  .goods-Material_left {
    width: 20%;
    margin-right: 10px;
  }
  .goods-Material_right {
    flex: 1;
  }
}
.out-dialog {
  width: 900px;
}
.el-tree {
  max-height: 480px;
  overflow-y: scroll;
}
.el-tree>.el-tree-node {
  display: inline-block;
  width: 100%;
}
</style>
